import os
import string
import pandas as pd
from numpy import random
from collections import Counter


## 统计元素
def count_analysis(df):
    all_elements = df.values.flatten()
    return Counter(all_elements)

def create_fold(fold_name,current_directory,parent_fold):
    """
    在当前目录下找到文件夹"parent_fold",并在该文件夹下创建一个新文件夹fold_name
    param:
    fold_name->string
    parent_fold->string
    current_directory:当前目录的文件路径    
    return:PATH_NAME->file's path 创建后的文件夹路径
    """
  
    files_directory = os.listdir(current_directory) #当前文件目录下的文件及文件夹
    is_fold = parent_fold in files_directory
    if is_fold:
        PATH_NAME = os.path.join(current_directory,
                            parent_fold,fold_name) 
        os.makedirs(PATH_NAME, exist_ok=True)
        print(f"创建了新的文件夹: {PATH_NAME}")
    else:
        PATH_NAME = None
        print(f'文件夹不存在{PATH_NAME}')
    return PATH_NAME

def generate_data(rows,columns):
    '''
    按照指定行列数生成随机字母数据，并将其转换为DataFrame类型的变量
    :param:row:指定的行数
    :param:columns:指定列数
    :return:df
    '''
    columns_name = [f'col_{i+1}' for i in range(columns)]
    letters = string.ascii_letters
    random_data = random.choice(list(letters),size=(rows,columns))
    return pd.DataFrame(random_data,columns=columns_name)

## 数据文件保存
def data_save(elements_data,file_path,result_name):
    data = pd.DataFrame.from_dict(elements_data,orient='index',columns=['count'])
    data.index_name = 'elements'
    total_file_path = os.path.join(file_path,result_name)
    data.to_csv(total_file_path)

def main():
    ## 定义生成的DataFrame数据变量的维数
    ROWS = 40
    COLS = 12

    ## 定义生成的文件个数和文件命名格式
    GENERATE_N = 10
    GENERATE_FILE = 'gen'
    RESULT_FILE = 'result'

    ## 得到文件路径：用于存放后面的随机生成的数据文件和元素查找结果的文件
    GENERATE_DATA = ['TEST','Data']
    OUTPUT_DATA = ['RESULT','Output']
    current_directory = 'D:\ProgramFile2_OR\Study_Practice_Share\weblog'
    
    data_file_path = create_fold(GENERATE_DATA[0],current_directory,GENERATE_DATA[1])
    output_file_path = create_fold(OUTPUT_DATA[0],current_directory,OUTPUT_DATA[1])

    ## 循环处理逻辑：根据所定义的生成文件数量，我们利用预先设计的函数实现项目需求
    for id in range(GENERATE_N):
        gen_file = GENERATE_FILE+str(id+1)+'.csv'
        result_file = RESULT_FILE+str(id+1)+'.csv'
        df = generate_data(ROWS,COLS) #生成数据
        df.to_csv(os.path.join(data_file_path,gen_file))
        element_data = count_analysis(df)
        data_save(element_data,output_file_path,result_file)

if __name__ == '__main__':
    main()


    
